﻿using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class LevelManager : MonoBehaviour
{
    public static LevelManager Instance;
    private void Awake()
    {
        if (Instance == null) 
        {
            Instance = this;
        }
    }



    [SerializeField]private List<GameObject> _levels = new List<GameObject>();
    [SerializeField] private GameObject _player;

    private Transform _connectPos;
    private Transform _playerStartPos;

    private int _currentIndex;
    private GameObject _curentLevel;
    private GameObject _nextLevel;
    private GameObject _curentPlayer;
    public void InitLevel()
    {
        ClearAll();

        _currentIndex = 0;
        _curentLevel = GameObject.Instantiate(_levels[_currentIndex], transform);
        _playerStartPos = _curentLevel.transform.Find("PlayerStartPosition");
        _curentPlayer = GameObject.Instantiate(_player, _playerStartPos.position, Quaternion.identity);
    }

    private void ClearAll()
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            Destroy(transform.GetChild(i).gameObject);
        }
    }

    private void OnEnable()
    {
        EventCenter.AddEventListener(EventName.LEVEL_TRIGGER,LoadNextLevel);
    }

    private void OnDisable()
    {
        EventCenter.AddEventListener(EventName.LEVEL_TRIGGER,LoadNextLevel);   
    }

    private void LoadLevel(int num)
    {
        if (num >= _levels.Count) 
        {
            num = 0;
        }
        _connectPos = _curentLevel.transform.Find("ConnectPos");
        _nextLevel =GameObject.Instantiate(_levels[num],transform);
        _nextLevel.transform.position = _connectPos.position;
        _curentLevel = _nextLevel;
    }
    private void LoadNextLevel()
    {
        _currentIndex++;
        LoadLevel(_currentIndex);
    }
}
